/* 
 * Copyright (C) 2011 rccloud.com All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rccloud.inproxy.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * Package scanner, it used to scan all classes in packages.
 */
public class PackageScanner {

	/**
	 * Get all classes in packages
	 * 
	 * @param packageNames
	 *            Package name
	 * @return All classes
	 * @throws PackageScanException
	 */
	public static List<String> scanClasses(String[] packageNames)
			throws PackageScanException {
		List<String> classes = new ArrayList<String>();
		for (String name : packageNames) {
			classes.addAll(scanClasses(name));
		}
		return classes;
	}

	/**
	 * Get all classes in package
	 * 
	 * @param packageName
	 *            Package name
	 * @return All classes
	 * @throws PackageScanException
	 */
	public static List<String> scanClasses(String packageName)
			throws PackageScanException {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		return scanClasses(loader, packageName);
	}

	/**
	 * Get all classes in package
	 * 
	 * @param loader
	 *            The class loader
	 * @param packageName
	 *            Package name
	 * @return All classes
	 * @throws PackageScanException
	 */
	public static List<String> scanClasses(ClassLoader loader,
			String packageName) throws PackageScanException {
		List<String> classes = new ArrayList<String>();
		String path = packageName.replace('.', '/').trim();
		Enumeration<URL> resources;
		try {
			resources = loader.getResources(path);
		} catch (IOException e) {
			throw new PackageScanException("Can't scan packages.");
		}
		if (resources != null) {
			while (resources.hasMoreElements()) {
				String filePath = resources.nextElement().getFile();
				if (filePath != null) {

					// WINDOWS HACK
					if (filePath.indexOf("%20") > 0)
						filePath = filePath.replaceAll("%20", " ");

					if ((filePath.indexOf("!") > 0)
							& (filePath.indexOf(".jar") > 0)) {
						String jarPath = filePath.substring(0,
								filePath.indexOf("!")).substring(
								filePath.indexOf(":") + 1);
						// WINDOWS HACK
						if (jarPath.indexOf(":") >= 0)
							jarPath = jarPath.substring(1);

						// Scan in jar file
						try {
							classes.addAll(getFromJARFile(jarPath, path));
						} catch (IOException e) {
							throw new PackageScanException(
									"Can't scan packages inside this jar file["
											+ jarPath + "].");
						}
					} else {
						// Scan in directory
						classes.addAll(getFromDirectory(new File(filePath),
								packageName));
					}
				}
			}
		}
		return classes;
	}

	/**
	 * Get classes from directory
	 * 
	 * @param directory
	 *            Directory for scanning
	 * @param packageName
	 *            Base package name
	 * @return Found classes
	 */
	private static List<String> getFromDirectory(File directory,
			String packageName) {
		List<String> classes = new ArrayList<String>();
		if (directory.exists()) {
			for (File file : directory.listFiles()) {
				if (file.isDirectory()) {
					classes.addAll(getFromDirectory(file, packageName + "."
							+ file.getName()));
				} else if (file.getName().endsWith(".class")) {
					String fileName = file.getName();
					String name = packageName + '.'
							+ fileName.substring(0, fileName.length() - 6);
					classes.add(name);
				}
			}
		}
		return classes;
	}

	/**
	 * Get classes from jar file
	 * 
	 * @param jar
	 *            Jar file
	 * @param packageName
	 *            Base package name
	 * @return Found classes
	 * @throws IOException
	 */
	private static List<String> getFromJARFile(String jar, String packageName)
			throws IOException {
		List<String> classes = new ArrayList<String>();
		JarInputStream jarFile = new JarInputStream(new FileInputStream(jar));
		JarEntry jarEntry;
		do {
			jarEntry = jarFile.getNextJarEntry();
			if (jarEntry != null) {
				String className = jarEntry.getName();
				if (className.endsWith(".class")) {
					className = className.substring(0, className.length() - 6);
					if (className.startsWith(packageName)) {
						classes.add(className.replace('/', '.'));
					}
				}
			}
		} while (jarEntry != null);
		return classes;
	}
}
